import { ReqPage } from "@/api/interface";
import { serviceList, serviceRemove, serviceStart, serviceStop } from "@/api/modules/service/service";
import Empty from "@/components/Empty";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import OnlineStatus from "@/components/Sansan/Status/OnlineStatus";
import { MessageType } from "@/enums/messageEnum";
import { RouterPath } from "@/enums/routerPath";
import { ServiceStatusTypes } from "@/enums/statusEnum";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { PublicStore } from "@/stores/modules/public";
import { getDictObj } from "@/utils/cacheUtil";
import { dataFormat } from "@/utils/format";
import { confirm, showMsg, showTips } from "@/utils/util";
import { gotoPage } from "../../../utils/routerUtil";
import AppletImg from "./../../../assets/images/applet/applet.png";
import DockerImg from "./../../../assets/images/applet/docker.png";
import BasicDialog from "./components/detailDialog";
import LoggerDialog from "./components/loggerDialog";
import { ComponentInternalInstance, getCurrentInstance } from "vue";
export default defineComponent({
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const publicStore = PublicStore();
		const serviceStatusLabels = ref<any>({});
		const initParam = reactive<ReqPage>({
			pageIndex: 0,
			pageSize: 20
		});

		const dataCallback = (data: any) => {
			return {
				datalist: data.records,
				total: data.total || 0,
				pageIndex: data.current,
				pageSize: data.size
			};
		};

		const getTableList = async (params: any) => {
			return serviceList({ ...params, appId: "ssiot" });
		};
		const buttonsList = ref<any>([]);
		onMounted(async () => {
			// 获取页面按钮权限
			buttonsList.value = await useAuthButtons();
			serviceStatusLabels.value = await getDictObj("service_status");
		});
		const detailDialog = reactive<any>({
			detail: {},
			title: "",
			visible: false
		});
		const loggerDialog = reactive<any>({
			detail: {},
			title: proxy?.$t("servicelist.dialog_title.logger"),
			visible: false
		});
		const clickBtn = async (fn: string, row: any) => {
			if (row.id && !row.selectList) {
				row = { selectList: [row], selectedListIds: [row.id] };
			}
			switch (fn) {
				case "add":
					detailDialog.detail = { svcType: "applet", machine: "local" };
					detailDialog.title = proxy?.$t("servicelist.dialog_title.add");
					detailDialog.visible = true;
					break;
				case "add-remote":
					detailDialog.detail = { svcType: "applet" };
					detailDialog.title = proxy?.$t("servicelist.dialog_title.add-remote");
					detailDialog.visible = true;
					break;
				case "mod":
					if (row.selectList.length != 1) {
						showMsg(proxy?.$t("servicelist.msg.mod"), MessageType.warning);
						return;
					}
					detailDialog.detail = { ...row.selectList[0] };
					detailDialog.title = proxy?.$t("servicelist.dialog_title.mod");
					detailDialog.visible = true;
					break;
				case "detail":
					if (row.selectList.length != 1) {
						showMsg(proxy?.$t("servicelist.msg.detail"), MessageType.warning);
						return;
					}
					detailDialog.detail = { ...row.selectList[0], readonly: true };
					detailDialog.title = proxy?.$t("servicelist.dialog_title.detail");
					detailDialog.visible = true;
					break;
				case "del":
					submitDel(row.selectList);
					break;
				case "stop":
					stop(row);
					break;
				case "start":
					start(row);
					break;
				case "logger":
					if (row.selectList && row.selectList.length != 1) {
						showMsg(proxy?.$t("servicelist.msg.logger"), MessageType.warning);
						return;
					}
					let info = { ...((row.selectList && row.selectList[0]) || row.row) };
					loggerDialog.title = "【" + info.name + proxy?.$t("servicelist.dialog_title.runninglog");
					loggerDialog.detail = info;
					loggerDialog.visible = true;
					break;
			}
		};

		let refreshInterval: any = null;
		onMounted(() => {
			autoRefresh();
		});
		onBeforeUnmount(() => {
			if (refreshInterval) {
				clearTimeout(refreshInterval);
			}
		});

		const autoRefresh = async () => {
			// refreshInterval = setTimeout(async () => {
			await proTable.value.getTableList();
			// autoRefresh();
			// }, 1500);
		};
		// 表格配置项
		const columns: ColumnProps[] = [
			{ type: "selection", fixed: "left", width: "auto" },
			{ prop: "status", label: proxy?.$t("servicelist.form_label.status"), width: 130 },
			{ prop: "name", label: proxy?.$t("servicelist.form_label.name"), width: "200px", align: "left", search: { el: "input" } },
			{ prop: "bin", label: proxy?.$t("servicelist.form_label.bin"), width: "130px" },
			{ prop: "instanceId", label: proxy?.$t("servicelist.form_label.instanceid"), width: "180px", search: { el: "input" } },
			{ prop: "arg", label: proxy?.$t("servicelist.form_label.arg"), width: "180px" },
			{ prop: "path", label: proxy?.$t("servicelist.form_label.path"), width: "180px" },
			{ prop: "createTime", label: proxy?.$t("servicelist.form_label.createtime"), width: "170px" },
			{ prop: "updateTime", label: proxy?.$t("servicelist.form_label.updatetime"), width: "170px" },
			{ prop: "loginTime", label: proxy?.$t("servicelist.form_label.logintime"), width: "170px" },
			// { prop: "machine", label: "部署节点", width: "130px" },
			// { prop: "version", label: "版本", width: "130px" },
			// { prop: "ip", label: "IP", width: "130px" },
			{ prop: "operate", label: proxy?.$t("servicelist.form_label.operate"), fixed: "right", width: 150 }
		];
		const proTable = ref<any>();
		const start = async (data: any) => {
			if (!data.selectList[0]) {
				showMsg(proxy?.$t("servicelist.msg.start"), MessageType.warning);
				return;
			}
			setTimeout(async () => {
				let { code, message } = await serviceStart({ id: data.selectList[0].id });
				showTips(code, proxy?.$t("servicelist.tips.start"), message) && proTable.value.getTableList();
			}, 1000);
		};
		const stop = (data: any) => {
			if (!data.selectList[0]) {
				showMsg(proxy?.$t("servicelist.msg.stop"), MessageType.warning);
				return;
			}
			setTimeout(async () => {
				let { code, message } = await serviceStop({ id: data.selectList[0].id });
				showTips(code, proxy?.$t("servicelist.tips.stop"), message) && proTable.value.getTableList();
			}, 1000);
		};
		const submitDel = async (dataList: any[]) => {
			if (!dataList.length) {
				showMsg(proxy?.$t("servicelist.msg.del"), MessageType.warning);
				return;
			}
			confirm({ content: proxy?.$t("servicelist.confirm_content.del") }).then(async flag => {
				if (!flag) {
					return;
				}
				let { code, message } = await serviceRemove({ id: dataList.map(item => item.id).join(",") });
				let ok = showTips(code, proxy?.$t("servicelist.tips.del"), message);
				if (ok) {
					proTable.value.clearSelection();
					proTable.value.reset();
				}
			});
		};
		const submitAdd = () => {
			detailDialog.visible = false;
			proTable.value.getTableList();
		};

		//上传网关程序
		const uploadParam = reactive({
			data: { id: "" },
			headers: { Authentication: "" }
		});
		const beforeUpload = (data: any) => {
			let selectList = data?.row ? [data?.row] : data?.selectList || [];
			if (selectList.length != 1) {
				showMsg(proxy?.$t("servicelist.msg.upload"), MessageType.warning);
				return;
			}
			uploadParam.data.id = selectList[0].id;
			uploadParam.headers.Authentication = publicStore.token;
			return true;
		};
		const uploadGatewaySuccess = async (res: any) => {
			let { code, message } = res;
			let ok = showTips(code, proxy?.$t("servicelist.tips.upload"), message);
			if (ok) {
				proTable.value.getTableList();
			}
		};
		const uploadGatewayError = async () => {
			showMsg(proxy?.$t("servicelist.msg.uploadfail"), false);
		};
		return () => {
			return (
				<div>
					{detailDialog.visible && (
						<BasicDialog
							width="700px"
							title={detailDialog.title}
							v-model:visible={detailDialog.visible}
							detail={detailDialog.detail}
							onSubmit={() => submitAdd()}
						/>
					)}
					<LoggerDialog
						width="1024px"
						title={loggerDialog.title}
						v-model:visible={loggerDialog.visible}
						detail={loggerDialog.detail}
						footerLabel={[proxy?.$t("servicelist.footer_label.close")]}
					/>
					<ProTable
						ref={proTable}
						title={buttonsList.value.length ? "" : proxy?.$t("servicelist.tab_title.service")}
						columns={columns}
						requestApi={getTableList}
						initParam={initParam}
						dataCallback={dataCallback}
					>
						{{
							tableHeader: (scope: any) => {
								return (
									<>
										{/* 添加权限：分类 */}
										{buttonsList.value.find((item: any) => item.btnGroup == "add") ? (
											<el-dropdown
												v-slots={{
													dropdown: () => {
														return (
															<el-dropdown-menu>
																{buttonsList.value
																	.filter((btn: any) => btn.btnGroup == "add")
																	.map((btn: any) => {
																		return (
																			<el-dropdown-item onClick={() => clickBtn(btn.path, scope)}>
																				{btn.menuName}
																			</el-dropdown-item>
																		);
																	})}
															</el-dropdown-menu>
														);
													}
												}}
											>
												<el-button type="primary" class="mr-2">
													{proxy?.$t("servicelist.btn.add")}
													<span class="el-icon--right iconfont iconchevron-down" />
												</el-button>
											</el-dropdown>
										) : null}

										{/* 其他按钮权限 */}
										{buttonsList.value?.map((item: any) => {
											return (
												<>
													{item.path == "upload" ? (
														<el-upload
															style="margin-left: 15px;float: right;"
															headers={uploadParam.headers}
															show-file-list={false}
															action="/api/service/bin/upload"
															before-upload={() => beforeUpload(scope)}
															on-success={uploadGatewaySuccess}
															on-error={uploadGatewayError}
															name="file"
															data={uploadParam.data}
														>
															<el-button class="iconfont iconbx-upload">{item.menuName}</el-button>
														</el-upload>
													) : item.btnGroup == "add" ? null : (
														<el-button onClick={() => clickBtn(item.path, scope)} type={item.btnClass}>
															<i class={`iconfont ${item.icon}`}></i>
															{item.menuName}
														</el-button>
													)}
												</>
											);
										})}
									</>
								);
							},
							status: (scope: any) => {
								return (
									<OnlineStatus
										labels={serviceStatusLabels.value}
										onlineLabel={proxy?.$t("servicelist.status.online")}
										offlineLabel={proxy?.$t("servicelist.status.offline")}
										types={ServiceStatusTypes}
										v-model={scope.row.status}
									></OnlineStatus>
								);
							},
							name: (scope: any) => {
								return (
									<el-link type="primary" onClick={() => clickBtn("detail", scope.row)}>
										<img style="height:18px;" src={scope.row.svcType == "dockerapp" ? DockerImg : AppletImg}></img>
										<span class="pl-2">{scope.row.name}</span>
									</el-link>
								);
							},
							loginTime: (scope: any) => {
								return dataFormat("datetime", scope.row.createTime);
							},
							updateTime: (scope: any) => {
								return dataFormat("datetime", scope.row.updateTime);
							},
							machine: (scope: any) => {
								return scope.row.machine == "local" ? (
									<span>{scope.row.machine}</span>
								) : (
									<el-link onClick={() => gotoPage(RouterPath.gatewayDetail, { sn: scope.row.machine })}>
										<span class="pl-2">{scope.row.machine}</span>
									</el-link>
								);
							},
							arg: (scope: any) => {
								return (
									<>
										{scope.row.arg ? (
											<span>
												<el-tooltip show-after={500} content={proxy?.$t("servicelist.tooltip.content")}>
													<i
														class="cursor-pointer iconfont iconbx-copy-alt pr-2"
														v-copy={`${scope.row.name} ${scope.row.arg}`}
													></i>
												</el-tooltip>
												<span>{scope.row.arg}</span>
											</span>
										) : (
											"--"
										)}
									</>
								);
							},
							operate: (scope: any) => {
								return (
									<>
										<el-link type="primary" link class="iconfont iconbx-file" onClick={() => clickBtn("logger", scope)}>
											{proxy?.$t("servicelist.operate.logger")}
										</el-link>
										<el-upload
											style="display:inline;margin-left: 10px;"
											headers={uploadParam.headers}
											show-file-list={false}
											action="/api/service/bin/upload"
											before-upload={() => beforeUpload(scope)}
											on-success={uploadGatewaySuccess}
											on-error={uploadGatewayError}
											name="file"
											data={uploadParam.data}
										>
											<el-link type="primary" link class="iconfont iconbx-file">
												{proxy?.$t("servicelist.operate.update")}
											</el-link>
										</el-upload>
										{/* <el-link type="primary" link class="iconfont iconbx-file" onClick={() => clickBtn("logger", scope)}>
											配置
										</el-link>
										<el-link type="primary" link class="iconfont iconbx-file" onClick={() => clickBtn("logger", scope)}>
											状态
										</el-link> */}
									</>
								);
							},
							empty: () => {
								return (
									<div>
										<Empty
											class="text-left leading-6"
											subtitle={proxy?.$t("servicelist.empty.subtitle")}
											show-button={false}
											// btnText="添加服务"
											// onAdd={(scope: any) => clickBtn("add", scope)}
										/>
									</div>
								);
							}
						}}
					</ProTable>
				</div>
			);
		};
	}
});
